import java.util.List;

public class OJProblem {

    //节点类
    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode head;

        public void createList() {
            ListNode node1 = new ListNode(12);
            ListNode node2 = new ListNode(23);
            ListNode node3 = new ListNode(34);
            ListNode node4 = new ListNode(45);
            ListNode node5 = new ListNode(56);

            node1.next = node2;
            node2.next = node3;
            node3.next = node4;
            node4.next = node5;

            this.head = node1;

        }
    }

    public ListNode head;

    //判断是不是回文数
    public boolean chPalindrome() {
        if(head == null) {
            return true;
        }
        //1.找中间节点
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
        }
        //2.slow的位置就是中间位置，开始翻转
        ListNode cur = slow.next;
        while(cur != null) {
            ListNode curN = cur.next;
            cur.next = slow;
            slow = cur;
            cur = curN;
        }
        //3.开始判断回文
        while(slow != head) {
            if(head.val != slow.val) {
                return false;
            }
            //只有一个节点
            if(head.next == slow) {
                return true;
            }
            head = head.next;
            slow = slow.next;
        }
        return true;
    }

    //判断是否有环
    public boolean hasCycle() {
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                return true;
            }
        }
        return false;
    }

    //如何在链表中创造环
    public void createLoop() {
        ListNode cur = head;
        while(cur.next != null) {
            cur = cur.next;
        }
        cur.next = head.next.next;
    }

    public ListNode detectCycle() {
        ListNode fast = head;
        ListNode slow = head;
        while(fast != null && fast.next != null) {
            fast = fast.next.next;
            slow = slow.next;
            if(fast == slow) {
                break;
            }
        }

        if(fast == null || fast.next == null) {
            return null;//没环
        }

        fast = head;
        while(fast != slow) {
            fast = fast.next;
            slow = slow.next;
        }
        return fast;
    }
}
